package _2022.hot100._6_Z字形变换;

import java.util.ArrayList;
import java.util.List;

/**
 * @author： YHSimon
 * @date： 2022-03-28 16:27
 */
public class Solution {
    //36ms
    public String convert(String s, int r) {
        int len=s.length();
        if(r<2){
            return s;
        }
        int c=(len/(2*r-2))*(r-1)+r-1;
        char[][] res=new char[r][c];
        int count=0;
        int i=0,j=0;
        int epoch=1;
        while(count<len){
            while(i<r&&count<len){
                res[i][j]=s.charAt(count++);
                i++;
            }
            i--; //修正
            //定位
            i--;
            j++;
            while(i>0&&j<epoch*(r-1)&&count<len){
                res[i][j]=s.charAt(count++);
                i--;
                j++;
            }
            epoch++;
        }
        StringBuilder sb=new StringBuilder();
        for(int m=0;m<r;m++){
            for(int n=0;n<c;n++){
                if(res[m][n]!=0){
                    sb.append(res[m][n]);
                }
            }
        }
        return sb.toString();
    }


    //推荐  模拟
    public String convert2(String s, int numRows) {
        if(numRows<2){
            return s;
        }
        List<StringBuilder> rows = new ArrayList<>();
        for(int i=0;i<numRows;i++) rows.add(new StringBuilder());
        int i=0,flag=-1;
        for(char c:s.toCharArray()){
            rows.get(i).append(c);
            if(i==0||i==numRows-1) flag=-flag;
            i+=flag;
        }
        StringBuilder res = new StringBuilder();
        for(StringBuilder row:rows) res.append(row);
        return res.toString();
    }


    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.convert("PAYPALISHIRING", 3));
    }
}
